package com.sheledon.flyCat.core.aop.proxy;

import com.sheledon.flyCat.core.aop.intercept.Interceptor;
import com.sheledon.flyCat.core.aop.intercept.MethodInvocation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy implements InvocationHandler {
    private final Object target;
    private final Interceptor interceptor;

    public JdkProxy(Object target, Interceptor interceptor) {
        this.target = target;
        this.interceptor = interceptor;
    }
    public static Object wrap(Object target,Interceptor interceptor){
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new JdkProxy(target,interceptor));
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args){
        MethodInvocation methodInvocation = new MethodInvocation(target,method,args);
        return interceptor.intercept(methodInvocation);
    }
}
